<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鼠标事件</title>
    <style>
        *{margin: 0;padding:0;box-sizing: border-box}
        .outer{
            width: 400px;
            height: 400px;
            border:solid 10px #000;
            display:flex;
            justify-content: center;
            align-items: center;
            margin: 50px auto;
            position:relative;
        }

        .inner{
            width: 200px;
            height: 200px;
            border:solid 1px rgb(107, 22, 22);
            position:absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div id="root"></div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{

            change = (e) => {
                //1. 获取事件源
                // console.log(e.target);
                e.target.style.background = 'orange';
            }

            jump = (e) => {
                //2. 阻止默认行为
                e.preventDefault();
                //3. 阻止冒泡
                e.stopPropagation();
            }

            // handleMouseMove
            handleMouseMove = (e) => {
                //获取鼠标距离左侧的偏移量
                let x = e.pageX;
                //获取小元素的宽度一半
                let w = this.inner.offsetWidth / 2;
                //获取 outer 元素距离左侧的偏移量
                let l = this.outer.offsetLeft;
                //计算
                let newLeft = x - w - l;
                //计算最大的left
                let maxLeft = this.outer.clientWidth - this.inner.offsetWidth;
                //判断
                if(newLeft <= 0) newLeft = 0;
                if(newLeft >= maxLeft) newLeft = maxLeft;
                
                //设置 修改 inner 元素 left
                this.inner.style.left = newLeft + 'px';
            }

            render(){
                return <div className="outer" ref={el => this.outer = el} onClick={this.change} onMouseMove={this.handleMouseMove}>
                        <div className="inner" onClick={this.change} ref={el => this.inner = el}>
                            <a href="http://atguigu.com" onClick={this.jump}>尚硅谷</a>    
                        </div>
                    </div>
            }
        }

        ReactDOM.render(<App /> ,document.querySelector("#root"));
    </script>
</body>
</html>